package com.taotao.tools.codec.sha;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SHA256Utils {
    public static String encrypt(byte[] input) throws NoSuchAlgorithmException {
        MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
        sha256.update(input);
        // 计算哈希值
        byte[] hash = sha256.digest();
        // 将哈希值转化为十六进制字符串
        String encrypted = DatatypeConverter.printHexBinary(hash);
        return encrypted;
    }

    public static String encrypt(String input) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        return encrypt(input.getBytes("UTF-8"));
    }

    public static String encrypt(File input) throws NoSuchAlgorithmException {
        return encrypt(FileUtils.readFile(input));
    }

}